package com.taptech.doufu.ui.activity.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.taptech.doufu.app.MyActivityManager;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.manager.UserLogManager;
import com.taptech.doufu.umeng.push.PushManager;
import com.taptech.doufu.sdk.google.IabBroadcastReceiver;
import com.taptech.doufu.sdk.google.IabHelper;
import com.taptech.doufu.sdk.google.IabResult;
import com.taptech.doufu.sdk.google.Inventory;
import com.taptech.doufu.sdk.google.Purchase;
import com.taptech.doufu.ui.activity.MainHomeActivity;
import com.taptech.doufu.util.SmartBarUtils;
import com.taobao.weex.IWXRenderListener;
import com.taobao.weex.WXSDKInstance;
import com.taobao.weex.common.WXRenderStrategy;
import com.taobao.weex.utils.WXResourceUtils;
import com.taptech.doufu.util.TTLog;
import com.taptech.doufu.weex.TFWXUtil;
import com.taptech.doufu.weex.http.TFHttpError;
import com.taptech.doufu.weex.http.TFHttpResponse;
import com.taptech.doufu.weex.http.TFHttpUtil;
import com.taptech.doufu.weex.statusbar.StatusBarCompat;
import com.taptech.doufu.R;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.listener.PublicInterface;
import com.taptech.doufu.services.personalcenter.WeiboService;
import com.taptech.doufu.util.SoftKeyboardUtil;
import com.taptech.doufu.util.NotifyUtil;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;
import com.umeng.analytics.MobclickAgent;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressLint("NewApi")
public class DiaobaoBaseActivity extends RxAppCompatActivity implements SoftKeyboardUtil.OnSoftKeyboardChangeListener, IabBroadcastReceiver.IabBroadcastListener {
    protected NotificationManager notificationManager;

    private WindowManager manager;
    private WindowManager.LayoutParams params;
    private TextView shadeBg;

    // 请求结果生命周期与activity同步
    public ArrayList<Object> reqestResCache = new ArrayList<Object>();

    public ArrayList<Object> mPresentWXSDKInstances;

    public TFActivityListener activityListener;

    public interface TFActivityListener {
        void onActivityResult(int requestCode, int resultCode, Intent data);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyActivityManager.getInstance().pushActivity(this);
        changeDayModel();
        initWindow();
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD_MR1 && SmartBarUtils.hasSmartBar()) {
            getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
            if (getActionBar() != null) {
                getActionBar().setDisplayOptions(0);
                SmartBarUtils.setActionBarViewCollapsable(getActionBar(), true);
            }
        } else {
            getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        }
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        this.tf_statusBarInit();
        SoftKeyboardUtil.observeSoftKeyboard(this, this);
        PushManager.getInstance().onAppStart(this);
    }

    public void updateStatusBar() {
        try {
            if (WeMediaApplication.getInstance().isDayNightMode_Night) {
                StatusBarCompat.setStatusBarColor(this, WXResourceUtils.getColor("#212222"), false);
            } else {
                StatusBarCompat.setStatusBarColor(this, WXResourceUtils.getColor("#ffffff"), true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 重写getResources()方法，让APP的字体不受系统设置字体大小影响
     */
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }


    protected void setStatusBarFullTransparent() {
//        if (Build.VERSION.SDK_INT >= 21 && Build.VERSION.SDK_INT <=29) {//21表示5.0
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LAYOUT_STABLE|View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
//        } else if (Build.VERSION.SDK_INT >= 19) {//19表示4.4
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//        }
    }

    protected void setHalfTransparent() {
        if (Build.VERSION.SDK_INT >= 21) {//21表示5.0
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN|View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        } else if (Build.VERSION.SDK_INT >= 19) {//19表示4.4
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    protected void tf_statusBarInit() {
        this.updateStatusBar();
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        if (!isActive) {
            isActive = true;
            //进入前台
            NotifyUtil.appEnterForeground();
        }
    }


    private boolean isActive = true; //是否在前台

    public boolean isActive() {
        return isActive;
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (!isAppOnForeground()) {
            //app 进入后台
            isActive = false;
            UserLogManager.uploadLocalLogs();
            NotifyUtil.appEnterBackground();
        }
    }


    public boolean isAppOnForeground() {
        ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = getApplicationContext().getPackageName();
        if (activityManager == null || TextUtils.isEmpty(packageName)) {
            return false;
        }
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            // The name of the process that this object is associated with.
            if (appProcess != null && appProcess.processName != null && appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }


    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
    }



    public Activity getThisActivity() {
        return this;
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!Constant.activityRun) {
                Intent intent = new Intent(this, MainHomeActivity.class);
                startActivity(intent);
                Constant.activityRun = true;
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    public void back(View v) {
        if (!Constant.activityRun) {
            Intent intent = new Intent(this, MainHomeActivity.class);
            startActivity(intent);
            Constant.activityRun = true;
            finish();
        } else {
            finish();
        }
    }

    public void changeDayModel() {
        if (WeMediaApplication.getInstance().isDayNightMode_Night) {
            setTheme(R.style.theme_dark);
        } else {
            setTheme(R.style.theme_day);
        }
    }

    private void initWindow() {
        manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.TYPE_APPLICATION,
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT);

        params.gravity = Gravity.TOP;
        params.y = 10;// 距离底部的距离是10像素 如果是 top 就是距离top是10像素

        shadeBg = new TextView(this);
        shadeBg.setBackgroundColor(0x66000000);
    }

    public void addShadeBg() {
        if (manager == null || !WeMediaApplication.getInstance().isDayNightMode_Night) {
            return;
        }
        try {
            manager.addView(shadeBg, params);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }

    // 在该页面弹出新的Weex页面

    public void presentWeexView(String url) {
        this.presentWeexView(url, null);
    }

    public void presentWeexView(String url, Map data) {
        try {
            HashMap option = new HashMap();
            option.put("bundleUrl", url);

            if (data instanceof Map) {
                option.put("data", data);
            }
            String newUrl = TFWXUtil.handleWXUrl(url);

            final WeakReference<DiaobaoBaseActivity> weakSelf = new WeakReference<DiaobaoBaseActivity>(this);
            WXSDKInstance wXSDKInstance = new WXSDKInstance(this);
            wXSDKInstance.registerRenderListener(new IWXRenderListener() {
                @Override
                public void onViewCreated(WXSDKInstance instance, View view) {
                    DiaobaoBaseActivity self = weakSelf.get();
                    if (self != null) {
                        view.setBackgroundColor(Color.argb(0, 0, 0, 0));
                        self.addContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));


                    }
                }

                @Override
                public void onRenderSuccess(WXSDKInstance instance, int width, int height) {
                    instance.getRootView().bringToFront();
                }

                @Override
                public void onRefreshSuccess(WXSDKInstance instance, int width, int height) {

                }

                @Override
                public void onException(WXSDKInstance instance, String errCode, String msg) {

                }
            });
            if (newUrl.startsWith("http") == true) {
                wXSDKInstance.renderByUrl("TF", newUrl, option, null, -1, -1, WXRenderStrategy.APPEND_ASYNC);
            } else {
                wXSDKInstance.render("TF", newUrl, option, null, -1, -1, WXRenderStrategy.APPEND_ASYNC);
            }

            if (mPresentWXSDKInstances == null) {
                mPresentWXSDKInstances = new ArrayList<Object>();
            }
            mPresentWXSDKInstances.add(wXSDKInstance);


        } catch (Exception e) {

        }

    }

    // 移除
    public void removeWeexView(WXSDKInstance instance) {
        try {
            if (mPresentWXSDKInstances != null) {
                if (mPresentWXSDKInstances.contains(instance)) {

                    ViewGroup parentView = (ViewGroup) instance.getContainerView().getParent();
                    parentView.removeView(instance.getContainerView());
                    instance.onActivityDestroy();
                    mPresentWXSDKInstances.remove(instance);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    @Override
    public void onSoftKeyBoardChange(int softKeyboardHeight, boolean visible) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (mHelper == null) {
            handlerMyData(requestCode, resultCode, data);
            return;
        }
        // Pass on the activity result to the helper for handling
        if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
            // not handled, so handle it ourselves (here's where you'd
            // perform any handling of activity results not related to in-app
            // billing...
            handlerMyData(requestCode, resultCode, data);
        } else {
            TTLog.d("DiaobaoBaseActivity", "onActivityResult handled by IABUtil.");
        }

    }

    private void handlerMyData(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (this.activityListener != null) {
            this.activityListener.onActivityResult(requestCode, resultCode, data);
        }

//        if (WeiboService.getInstance().mSsoHandler != null) {
//            try {
//                WeiboService.getInstance().mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
//            } catch (NullPointerException e) {
//                e.printStackTrace();
//            }
//        }
    }


    /**
     * 缩小返回动画
     *
     * @param context
     */
    public static void exitAnimShrink(Context context) {
        ((Activity) context).overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
    }

    /**
     * 淡出动画
     *
     * @param context
     */
    public static void exitAnimAlpha(Context context) {
        ((Activity) context).overridePendingTransition(R.anim.enteralpha, R.anim.exitalpha);
    }

    /**
     * 淡入动画
     *
     * @param context
     */
    public static void enterAnimAlpha(Context context) {
        ((Activity) context).overridePendingTransition(R.anim.enteralpha, R.anim.exitalpha);
    }


    private List<String> pList = new ArrayList<>();  //商品列表
    IabHelper mHelper;
    IabBroadcastReceiver mBroadcastReceiver;
    static final int RC_REQUEST = 10001;

    public void initGooglePay() {
        getPurchaseList();
        String base64EncodedPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtzRGdhcBEcmacrdGJV0xw/W2MVzP0owO4YaPB4LSS2XsxkYw8/6iydOMgL0LJMSqIyjvKcXuihytGsgYC1svjUMSDzBKY6XZzPKP50HARTgRCFt+IjDRR0KktR8CjOoVbRuB889OVpIkLyigLa9airj55mSli2os4V3qIGgm3ngNLepo0M3+wG2sh+tiTldL/MVedmKSeP/+zCcvtp3AcMiIA0eZei3QeHEhh2mzpgW08wD1d6871AOvQABfFu0rMITP/lrawrouUJjRd2FlLMhT7EAi6an/vfBKPppw+8IdRAKs+jIuAcWnyDtD7SKYqe6CoDkP1Hwpf6WzaOLTdwIDAQAB";
        mHelper = new IabHelper(this, base64EncodedPublicKey);
        mHelper.enableDebugLogging(true);
        mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
            public void onIabSetupFinished(IabResult result) {
                if (!result.isSuccess()) {
                    return;
                }
                if (mHelper == null) return;
                mBroadcastReceiver = new IabBroadcastReceiver(DiaobaoBaseActivity.this);
                IntentFilter broadcastFilter = new IntentFilter(IabBroadcastReceiver.ACTION);
                registerReceiver(mBroadcastReceiver, broadcastFilter);
                try {
                    mHelper.queryInventoryAsync(mGotInventoryListener);
                } catch (IabHelper.IabAsyncInProgressException e) {
                }
            }
        });
    }


    /**
     * 获取商品列表
     */
    private void getPurchaseList() {
        TFHttpUtil.requestGet("http://api.doufu.la/google/getAllProducts", null, new TFHttpResponse() {
            @Override
            public void onResponse(JSONObject json, TFHttpError error) {
                try {
                    pList = JSONArray.parseArray(json.getJSONObject("data").getJSONArray("list").toString(), String.class);
                } catch (Exception e) {

                }
            }
        });
    }

    /**
     * 查询未消耗的订单
     */
    IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
        public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
            if (mHelper == null) return;
            if (result.isFailure()) {
                return;
            }
            for (String pID : pList) {
                final Purchase purchase = inventory.getPurchase(pID);
                if (purchase != null) {
                    verifyDeveloperPayload(purchase, new PublicInterface.OnBooleanResult() {
                        @Override
                        public void onResult(boolean result) {
                            if (result) {
                                try {
                                    mHelper.consumeAsync(purchase, mConsumeFinishedListener);
                                } catch (IabHelper.IabAsyncInProgressException e) {
                                }
                            }
                        }
                    });
                }
            }
        }
    };

    @Override
    public void receivedBroadcast() {
        try {
            mHelper.queryInventoryAsync(mGotInventoryListener);
        } catch (IabHelper.IabAsyncInProgressException e) {
        }
    }


    public void googlePay(final String pID, int optionId) {
        HashMap params = new HashMap();
        params.put("option_id", optionId);
        TFHttpUtil.requestGet("http://api.doufu.la/google/createOrder", params, new TFHttpResponse() {
            @Override
            public void onResponse(JSONObject json, TFHttpError error) {
                if (json != null && json.containsKey("data")
                        && json.getJSONObject("data") != null
                        && json.getJSONObject("data").containsKey("payload")
                        && !TextUtils.isEmpty(json.getJSONObject("data").getString("payload"))) {
                    String payload = json.getJSONObject("data").getString("payload");
                    try {
                        mHelper.launchPurchaseFlow(DiaobaoBaseActivity.this, pID, RC_REQUEST,
                                mPurchaseFinishedListener, payload);
                    } catch (Exception e) {
                        makeText(e.getMessage());
                    }
                } else {
                    makeText("支付失败，请重试");
                }
            }
        });
    }

    /**
     * 支付验证
     *
     * @param p
     * @return
     */
    private void verifyDeveloperPayload(Purchase p, final PublicInterface.OnBooleanResult onBooleanResult) {
        HashMap params = new HashMap();
        params.put("inapp_purchase_data", p.getOriginalJson());
        params.put("inapp_data_signature", p.getSignature());
        TFHttpUtil.requestPost("http://api.doufu.la/google/verifyOrder", params, new TFHttpResponse() {
            @Override
            public void onResponse(JSONObject json, TFHttpError error) {
                try {
                    boolean handleStatus = json.getJSONObject("data").getBoolean("handleStatus");
                    int verify = json.getJSONObject("data").getInteger("verify");
                    if (handleStatus && verify == 1) {
                        //验证成功
                        onBooleanResult.onResult(true);
                    } else {
                        //验证失败
                        onBooleanResult.onResult(false);
                    }
                } catch (Exception e) {
                    //验证失败
                    onBooleanResult.onResult(false);
                }
            }
        });
    }

    /**
     * 购买回调
     */
    IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
        public void onIabPurchaseFinished(IabResult result, final Purchase purchase) {
            if (mHelper == null) return;
            if (result.isFailure()) {
                makeText("支付失败，请重试");
                return;
            }

            verifyDeveloperPayload(purchase, new PublicInterface.OnBooleanResult() {
                @Override
                public void onResult(boolean result) {
                    if (result) {
                        try {
                            mHelper.consumeAsync(purchase, mConsumeFinishedListener);
                        } catch (IabHelper.IabAsyncInProgressException e) {
                        }
                    }
                }
            });
        }
    };

    /**
     * 消耗完成回调
     */
    IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() {
        public void onConsumeFinished(Purchase purchase, IabResult result) {
            if (mHelper == null) return;
            if (result.isSuccess()) {
                //账单已消耗
                makeText("支付成功");
                NotifyUtil.googlePayNotifySuccess();
            } else {
                makeText("支付异常");
            }
        }
    };

    public void makeText(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBroadcastReceiver != null) {
            unregisterReceiver(mBroadcastReceiver);
        }
        if (mHelper != null) {
            mHelper.disposeWhenFinished();
            mHelper = null;
        }
        MyActivityManager.getInstance().popActivity(this);
    }
}
